package com.puppet.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching  //开启缓存
@Slf4j
public class CacheConfig extends CachingConfigurerSupport {

    /**
     * 自定义的缓存key生成策略
     */
    @Override
    @Bean   //放到Spring容器中
    public KeyGenerator keyGenerator() {
        //目标对象，方法，参数
        return (target, method, params) -> {
            //创建一个字符串拼接对象
            StringBuilder sb = new StringBuilder();
            //拼接业务类全名
            sb.append(target.getClass().getName()).append(":");
            //拼接方法名
            sb.append(method.getName()).append(":");
            //拼接参数
            for (Object obj : params) {
                sb.append(obj.toString()).append(":");
            }
            String key = sb.toString();
            log.info("生成的缓存key为:{}", key);
            return key;
        };
    }
}